<?php
class Mgmt extends Controller {
	
	private $_view_data;
	private $_current_blogger_uri;
	private $_current_blogger_id;
	private $_blog_info;
	private $_is_blog_owner;
	
	function Mgmt() {
		parent::Controller();
		
//		$this->output->enable_profiler(TRUE);
		
		// Enabled?
		$enabled = $this->config->item('Enabled');
		if(!$enabled) {
			show_error('OoW = Out of Work!');
		}
		
		$this->load->library('common');
		$this->load->library('auth');
		$this->load->library('cache');
		$this->load->library('user_agent');
		
		// I.B.M. ;)
		$this->load->model('Identity_Manager');
		$this->load->model('Blogger_Manager');
		$this->load->model('Message_Manager');
		
		// Language
		$this->lang->load('n8_mgmt');
	}
	
	function _setUp() {
		// init...
		$this->_current_blogger_uri = $this->common->GetCurrentBloggerURI();
		$this->_view_data['blogger_uri'] = $this->_current_blogger_uri;
		
		$this->_current_blogger_id = $this->common->GetBloggerID($this->_current_blogger_uri);
		if($this->_current_blogger_id <= 0) {
			show_error('Specified Blog does not exist!');
		}
		
		// blog basic info
		$this->_blog_info = $this->cache->Load('blog_basic_info_' . $this->_current_blogger_id);
		if(!$this->_blog_info) {
			$this->_blog_info = $this->Blogger_Manager->GetBloggerInfo($this->_current_blogger_id);
			$this->cache->Store('blog_basic_info_' . $this->_current_blogger_id, json_encode($this->_blog_info));
		} else {
			$this->_blog_info = json_decode($this->_blog_info);
		}
		$this->_view_data['blog_info'] = $this->_blog_info;
		
		// identity
		$this->Identity_Manager->DoIdentityCheck($this->_blog_info);
		$this->_is_blog_owner = $this->Identity_Manager->IsBlogOwner();
		
		$this->Message_Manager->SetCurrentBloggerID($this->_current_blogger_id);
	}
	
	function _check_messages() {
		// pm num
		$unread_pm_num = $this->Message_Manager->GetUnreadPMNum();
		$this->_view_data['unread_pm_num'] = $unread_pm_num;
	}
	
	function _check_owner() {
		if($this->_is_blog_owner == FALSE) {
			redirect('/' . $this->_current_blogger_uri . '/mgmt/login');
		}
	}
	
	// Show Dashboard
	function index($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		$this->_check_messages();
		
		$this->_view_data['emotag_im_linking_code'] = $this->_blog_info->id . '_' . md5($this->_blog_info->password);
		
		$this->load->view('mgmt/dashboard_view', $this->_view_data);
	}
	
	function emotag($blogger_uri, $page_no = 0) {
		$this->_setUp();
		
		$this->load->model('EmoTag_Manager');
		$this->EmoTag_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') { // add or delete
			$this->_check_owner();
			$oper = $this->input->post('oper');
			if($oper == 'add') {
				$pdata = json_decode($this->input->post('posted_data'));
				$result = '';
				if($pdata->icon != '' && $pdata->text != '') {
					$emoTag_data = array(
						'blogger' => $this->_current_blogger_id,
						'post_time' => $this->common->Now(),
						'emo_icon' => $pdata->icon,
						'emo_text' => $pdata->text
					);
					$this->EmoTag_Manager->AddEmoTag($emoTag_data);
					$result = 'SUCC_*';
				}
				echo($result);
			} elseif($oper == 'delete') {
				$emoTag_id = $this->input->post('id');
				$this->EmoTag_Manager->DeleteEmoTag($this->_current_blogger_id, $emoTag_id);
				echo('SUCC_*');
			}
		} else { // display
			$per_page = 3;
			$total_emotags = $this->EmoTag_Manager->CountEmoTags();
			$total_pages = ceil($total_emotags / $per_page);
			$prev = $page_no - 1;
			if($page_no == 0) {
				$prev = 0;
			}
			$next = $page_no + 1;
			if($next == $total_pages) {
				$next = $total_pages - 1;
			}
			$this->_view_data['prev_string'] = $prev;
			$this->_view_data['next_string'] = $next;
			$this->_view_data['paging_info'] = (string)($page_no + 1) . '/' . (string)$total_pages;
			
			$emoTags = $this->EmoTag_Manager->ListEmoTags($per_page, $page_no); // latest 3
			// proc for friendly time
			$now_time = $this->common->Now();
			foreach($emoTags as $em) {
				$em->post_time = $this->common->TimeDiff($em->post_time, $now_time);
			}
			$this->_view_data['emoTags'] = $emoTags;
			
			if($this->input->post("D")) {
				$this->_view_data['show_delete_icon'] = TRUE;
			} else {
				$this->_view_data['show_delete_icon'] = FALSE;
			}
			
			$this->load->view('mgmt/dashboard_emotag_list_view', $this->_view_data);
		}
	}
	
	// Entry-List Main
	function entries($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$this->load->model('Entry_Manager');
		$this->Entry_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$this->load->model('Tag_Manager');
		$this->Tag_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$this->load->model('Subscription_Manager');
		$this->Subscription_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			// proc batch entry operations
			$result = '';
			$oper = $this->input->post('operation');
			switch($oper) {
				case 'batch_change_category':
					$new_cate_id = $this->input->post('new_cate_id');
					$arr_ids = json_decode($this->input->post('posted_data'));
					if(is_array($arr_ids)) {
						$this->Entry_Manager->CategorizeEntries($arr_ids, $new_cate_id);
						// clean caches
						$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
						$this->cache->Remove('latest_entries');
						$result = 'SUCC_*';
					} else {
						$result = 'FAIL_NOT-ARRAY';
					}
					break;
				case 'batch_change_state':
					$new_state = $this->input->post('new_state');
					$arr_ids = json_decode($this->input->post('posted_data'));
					if(is_array($arr_ids)) {
						$this->Entry_Manager->BatchSetEntryState($arr_ids, $new_state);
						// clean caches
						$this->cache->Remove('blogger_list');
						$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_archive_list_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
						$this->cache->Remove('latest_entries');
						$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
						$this->cache->Remove('all_tags');
						$result = 'SUCC_*';
					} else {
						$result = 'FAIL_NOT-ARRAY';
					}
					break;
				case 'batch_delete':
					$arr_ids = json_decode($this->input->post('posted_data'));
					if(is_array($arr_ids)) {
						$this->Entry_Manager->BatchDeleteEntries($arr_ids);
						// remove related subscriptions
						$this->Subscription_Manager->EntriesRemovedAction($arr_ids);
						// clean caches
						$this->cache->Remove('blogger_list');
						$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_archive_list_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
						$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
						$this->cache->Remove('latest_entries');
						$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
						$this->cache->Remove('all_tags');
						$result = 'SUCC_*';
					} else {
						$result = 'FAIL_NOT-ARRAY';
					}
					break;
				case 'batch_set_tags':
					$new_tags = $this->_purge_tags($this->input->post('new_tags'));
					$arr_ids = json_decode($this->input->post('posted_data'));
					if(is_array($arr_ids)) {
						$this->Entry_Manager->BatchSetEntryTagInfo($arr_ids, $new_tags);
						// update tag-table too
						foreach($arr_ids as $eid) {
							$this->Tag_Manager->UpdateTags($new_tags, $eid);
						}
						// clean caches
						$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
						$this->cache->Remove('latest_entries');
						$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
						$this->cache->Remove('all_tags');
						$result = 'SUCC_*';
					} else {
						$result = 'FAIL_NOT-ARRAY';
					}
					break;
				case 'delete_entry':
					$entry_id = $this->input->post('entry_id');
					$this->Entry_Manager->DeleteEntry($entry_id);
					// remove related subscriptions
					$this->Subscription_Manager->EntryRemovedAction($entry_id);
					// clean caches
					$this->cache->Remove('blogger_list');
					$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_archive_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
					$this->cache->Remove('all_tags');
					$result = 'SUCC_*';
					break;
				default:
					break;
			}
			echo($result);
		} else {
			$this->_check_messages();
			
			// month list
			$month_list = $this->Blogger_Manager->GetBlogArchiveList($this->_current_blogger_id);
			$this->_view_data['month_list'] = $month_list;
			if(count($month_list) > 0) {
				$this->_view_data['latest_month'] = array($month_list[0]->year, $month_list[0]->month);
			} else {
				$this->_view_data['latest_month'] = array(0, 0);
			}
			
			// last year-month?
			$current_visiting_month = $this->_view_data['latest_month'];
			$cv_year_month = $this->common->GetCookie('last_entries_list_year_month');
			if($cv_year_month !== FALSE) {
				$current_visiting_month = explode("_", $cv_year_month); // n/a
			}
			$this->_view_data['current_visiting_month'] = $current_visiting_month;
			
			// custom cates
			$cust_cates = $this->Blogger_Manager->GetBlogCustomCategoryList($this->_current_blogger_id);
			$this->_view_data['cust_cates'] = $cust_cates;
			
			// drafts
			$drafts = $this->Blogger_Manager->GetDraftList($this->_current_blogger_id);
			if(!is_null($drafts)) {
				$this->_view_data['draft_num'] = count($drafts);
			} else {
				$this->_view_data['draft_num'] = 0;
			}
			
			// tag list
			$tag_list = $this->Tag_Manager->GetTagList();
			$this->_view_data['tag_list'] = $tag_list;
			
			$this->output->set_header('Cache-Control: no-cache, must-revalidate');
			$this->output->set_header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
			
			$this->load->view('mgmt/entries_view', $this->_view_data);
		}
	}
	// Entry-List get list via Ajax
	function entries_list($blogger_uri, $year, $month) {
		$this->_setUp();
		$this->_check_owner();
		
		// draft
		if($year == '0099' && $month == '00') { // special code -_-
			$month_entry_list = $this->Blogger_Manager->GetDraftList($this->_current_blogger_id);
			$this->_view_data['month_entry_list'] = $month_entry_list;
			$this->_view_data['entry_list_month_title'] = '网志列表：草稿';
		} else {
			// entry list by month
			$month_entry_list = $this->Blogger_Manager->GetEntriesByMonth($this->_current_blogger_id, $year, $month);
			$this->_view_data['month_entry_list'] = $month_entry_list;
			$this->_view_data['entry_list_month_title'] = '网志列表：' . $year . '年' . $month . '月';
		}
		$this->common->SetCookie('last_entries_list_year_month', $year . '_' . $month);
		
		$this->load->view('mgmt/entries_list_view', $this->_view_data);
	}
	
	function _serverside_check($entry_data) {
		// title and content cannot be empty
		$e_title = $entry_data->title;
		$e_content = $entry_data->content;
		if($e_title == '' || $e_content == '') {
			return FALSE;
		}
		$e_tags = $entry_data->tags;
		if($e_tags != '') {
			// php's regexp is different from javascript's
			if(preg_match('/[^\x{4E00}-\x{9FA0}a-zA-Z0-9._ ]/u', $e_tags)) {
				return FALSE;
			}
		}
		return TRUE;
	}
	
	function _purge_tags($ts) {
		$ps = trim($ts);
		$ps = preg_replace('/\s{2,}/', ' ', $ps);
		$aps = explode(' ', $ps);
		$aps = array_unique($aps);
		$ps = implode(' ', $aps);
		return $ps;
	}
	
	function edit_entry($blogger_uri, $entry_id) {
		$this->_setUp();
		$this->_check_owner();
		
		$this->load->model('Entry_Manager');
		$this->Entry_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$this->load->model('Tag_Manager');
		$this->Tag_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$draft_mode = TRUE;
		$entry_data = array(
			'id' => $entry_id,
			'title' => '',
			'expression' => '1',
			'category_id' => 1,
			'allow_comment' => TRUE,
			'state' => 1,
			'tags' => '',
			'content' => ''
		);
		$entry_data = (object)$entry_data;
		if($entry_id > 0) {
			$entry_data = $this->Entry_Manager->RetrieveEntry($entry_id);
			if(is_null($entry_data)) {
				show_error('No such Blog-Entry!');
			}
			if($entry_data->state < 99) {
				$draft_mode = FALSE;
			}
		}
		$this->_view_data['editing_draft'] = $draft_mode;
		$this->_view_data['entry_data'] = $entry_data;
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			// proc posted entry-data
			$now = $this->common->Now();
			$result = 'FAIL_*';
			$pdata = json_decode($this->input->post('posted_data'));
			$pdata->tags = $this->_purge_tags($pdata->tags);
			if($this->_serverside_check($pdata)) {
				$entry = array(
					'id' => $pdata->id,
					'blogger_id' => $this->_current_blogger_id,
					'post_time' => $now,
					'title' => $pdata->title,
					'author_name' => $this->_blog_info->user_name,
					'expression' => $pdata->expression,
					'ip' => $this->input->ip_address(),
					'category_id' => $pdata->category_id,
					'allow_comment' => $pdata->allow_comment ? 1 : 0,
					'state' => $pdata->state,
					'tags' => $pdata->tags,
					'entry_url' => '',
					'content' => $pdata->content
				);
				$oper = ($pdata->id == 0) ? 'create' : 'update';
				if($oper == 'create') {
					$new_entry_id = $this->Entry_Manager->AddEntry($entry);
					// if has tags, insert into Tags table
					if($entry['tags'] != '') {
						$this->Tag_Manager->AddTags($entry['tags'], $new_entry_id);
						$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
						$this->cache->Remove('all_tags');
						// blog_tag_cloud & all_tag_cloud?
					}
					// clean cache
					$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_archive_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blogger_list');
					$this->cache->Remove('latest_entries');
					// ...
					
					$result = 'SUCC_' . $new_entry_id;
				} elseif($oper == 'update') {
					// published entry cannot be changed back to draft
					if($entry_data->state == 99 || $entry['state'] < 99) {
						// if update a published entry, don't change post-time
						if($entry_data->state < 99) {
							$entry['post_time'] = $entry_data->post_time;
						}
						$this->Entry_Manager->UpdateEntry($entry);
						// if tags have been changed, update Tags table
						if($entry['tags'] != $entry_data->tags) {
							$this->Tag_Manager->UpdateTags($entry['tags'], $entry['id']);
							$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
							$this->cache->Remove('all_tags');
							// all-tags?
						}
						// if new state is still 99, then just update draft, so don't need to clear cache
						if($entry['state'] < 99) {
							// clean cache
							$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
							$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
							$this->cache->Remove('blog_archive_list_' . $this->_current_blogger_id);
							$this->cache->Remove('blogger_list');
							$this->cache->Remove('latest_entries');
							$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
							
							// update subscriptions
							$this->load->model('Subscription_Manager');
							$this->Subscription_Manager->SetCurrentBloggerID($this->_current_blogger_id);
							$this->Subscription_Manager->SetEntryUpdated($entry_id, $now);
						}
						$result = 'SUCC_*';
					}
				}
			}
			echo($result);
		} else {
			$this->_check_messages();
			
			// tag list
			$tag_list = $this->Tag_Manager->GetTagList();
			$this->_view_data['tag_list'] = $tag_list;
			
			// category list
			$cates_list = $this->Blogger_Manager->GetBlogCustomCategoryList($this->_current_blogger_id);
			$this->_view_data['custom_cates'] = $cates_list;
			
			// referer
			$http_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
			if($http_referer != '') {
				if(strpos($http_referer, "/mgmt") !== FALSE) {
					$http_referer = '';
				}
			}
			$this->_view_data['http_referer'] = $http_referer;
			
			$this->load->view('mgmt/edit_entry_view', $this->_view_data);
		}
	}
	
	function comments($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$this->load->model('Subscription_Manager');
		$this->Subscription_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			// proc batch delete or sth...
			$result = '';
			$oper = $this->input->post('operation');
			switch($oper) {
				case 'delete_subscription':
					$entry_id = $this->input->post('entry_id');
					$this->Subscription_Manager->RemoveSubscription($entry_id);
					$result = 'SUCC_*';
					break;
				case 'delete_comments':
					$arr_ids = json_decode($this->input->post('posted_data'));
					$this->Blogger_Manager->DeleteUnauthedComments($arr_ids);
					$result = 'SUCC_*';
					break;
				case 'auth_comments':
					$arr_ids = json_decode($this->input->post('posted_data'));
					$this->Blogger_Manager->AuthComments($arr_ids);
					// clean caches
					$this->cache->Remove('blogger_list');
					$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$result = 'SUCC_*';
					break;
				default:
					$result = 'FAIL_*';
					break;
			}
			echo($result);
		} else {
			$this->_check_messages();
			$this->load->view('mgmt/comments_view', $this->_view_data);
		}
	}
	
	function watches_list($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		// ...
		$this->load->model('Subscription_Manager');
		$this->Subscription_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$sub_list = $this->Subscription_Manager->ListMySubscription();
		$now = $this->common->Now();
		foreach($sub_list as $sl) {
			if(is_null($sl->user_url) || $sl->user_url == '') {
				$sl->user_url = $sl->blogger_id;
			}
			if($sl->state == 0) {
				$sl->title = '本条网志内容保密...';
			}
			$sl->update_time = $this->common->TimeDiff($sl->update_time, $now);
		}
		
		$this->_view_data['sub_list'] = $sub_list;
		
		$this->load->view('mgmt/comments_watches_list_view', $this->_view_data);
	}
	
	function comments_list($blogger_uri, $type) {
		$this->_setUp();
		$this->_check_owner();
		
		$this->_view_data['list_type'] = $type;
		$comments = null;
		if($type == 0) {
			// get unauthed comments
			$comments = $this->Blogger_Manager->GetUnauthedComments($this->_current_blogger_id);			
			foreach($comments as $c) {
				$c->post_time = $this->common->NicerTime($c->post_time);
			}
		} elseif($type == 1) {
			// get latest authed comments
			$comments = $this->Blogger_Manager->GetRecentComments($this->_current_blogger_id, 7); // 7 entries should be ok
		}
		$this->_view_data['comments'] = $comments;
		
		$this->load->view('mgmt/comments_list_view', $this->_view_data);
	}
	
	// Show Login-Box
	function login($blogger_uri = '') {
		$login_ok = TRUE;
		
		// mobile client check
		$agent_is_iphone = $this->agent->is_mobile();
		
		if($this->input->post('hidIsPostBack') == 'ja') {
			$user_name = $this->input->post('txtUserName');
			$user_pwd = $this->input->post('txtPassword');
			
			$authed_user = $this->auth->AuthByUserName($user_name, $user_pwd);
			if($authed_user !== FALSE) {
				// login done!
				$uri = $authed_user->user_url;
				if(is_null($uri) || $uri == '') {
					$uri = $authed_user->id; // -_-
				}
				$days = 14; // 2 weeks
				$this->Blogger_Manager->SetAuthInfo($authed_user->id, $user_pwd, FALSE, $days, $authed_user);
				
				if($agent_is_iphone) {
					redirect('/' . $uri);
				} else {
					redirect('/' . $uri . '/mgmt');
				}
			} else {
				$login_ok = FALSE;
			}
		}
		if($login_ok) {
			$this->_view_data['has_login_error'] = FALSE;
			$this->_view_data['login_error_msg'] = '';
		} else {
			$this->_view_data['has_login_error'] = TRUE;
			$this->_view_data['login_error_msg'] = lang('n8_mgmt_login_errorMsg');
		}
		if($agent_is_iphone) {
			$this->load->view('mobile/mgmt/login_view', $this->_view_data);
		} else {
			$this->load->view('mgmt/login_view', $this->_view_data);
		}
	}
	
	function logout($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$this->Blogger_Manager->Logout();
		redirect('/' . $this->_current_blogger_uri);
	}
	
	// CRUD for entry categories
	function categories($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		// tag list
		$this->load->model('Tag_Manager');
		$this->Tag_Manager->SetCurrentBloggerID($this->_current_blogger_id);
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			// proc posted data
			$this->load->model('Category_Manager');
			$this->Category_Manager->SetCurrentBloggerID($this->_current_blogger_id);
			
			$oper = $this->input->post('operation');
			$oper_result = '';
			switch($oper) {
				case 'create':
					$pdata = json_decode($this->input->post('posted_data'));
					$new_cate_id = $this->Category_Manager->AddCategory($pdata->title, $pdata->description);
					$this->cache->Remove('blog_custom_category_list_' . $this->_current_blogger_id);
					$oper_result = 'SUCC_' . $new_cate_id;
					break;
				case 'update':
					$pdata = json_decode($this->input->post('posted_data'));
					$this->Category_Manager->ModifyCategory($pdata->id, $pdata->title, $pdata->desc);
					$this->cache->Remove('blog_custom_category_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$oper_result = 'SUCC_*';
					break;
				case 'delete':
					$pdata = json_decode($this->input->post('posted_data'));
					$this->Category_Manager->RemoveCategory($pdata->id);
					$this->cache->Remove('blog_custom_category_list_' . $this->_current_blogger_id);
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$oper_result = 'SUCC_*';
					break;
				case 'rename_tag':
					$tag_to_rename = $this->input->post('tag_to_rename');
					$new_tag_string = $this->input->post('new_tag_string');
					$new_tag_string = $this->_purge_tags($new_tag_string); // no server-side tag validating
					$this->Tag_Manager->BatchRenameTag($tag_to_rename, $new_tag_string);
					// clean caches
					$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
					$this->cache->Remove('all_tags');
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$oper_result = 'SUCC_*';
					break;
				case 'delete_tag':
					$tag_to_delete = $this->input->post('tag_to_delete');
					$this->Tag_Manager->DeleteTag($tag_to_delete);
					// clean caches
					$this->cache->Remove('blog_tag_list_' . $this->_current_blogger_id);
					$this->cache->Remove('all_tags');
					$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
					$this->cache->Remove('latest_entries');
					$oper_result = 'SUCC_*';
					break;
				default:
					break;
			}
			echo($oper_result);
		} else {
			$this->_check_messages();
			
			$tag_list = $this->Tag_Manager->GetTagList();
			$this->_view_data['tag_list'] = $tag_list;
			
			$this->load->view('mgmt/categories_view', $this->_view_data);
		}
	}
	
	function categories_list($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		// category list
		$cates_list = $this->Blogger_Manager->GetBlogCustomCategoryList($this->_current_blogger_id);
		$this->_view_data['cates_list'] = $cates_list;
		
		$this->load->view('mgmt/categories_list_view', $this->_view_data);
	}
	
	function links($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			$this->load->model('Link_Manager');
			$this->Link_Manager->SetCurrentBloggerID($this->_current_blogger_id);
			
			$oper = $this->input->post('operation');
			$pdata = json_decode($this->input->post('posted_data'));
			$result = '';
			switch($oper) {
				case 'create':
					$new_link = array(
						'title' => $pdata->title,
						'url' => $pdata->url,
						'description' => $pdata->desc
					);
					$this->Link_Manager->AddLink($new_link);
					$result = 'SUCC_*';
					break;
				case 'update':
					$mod_link = array(
						'id' => $pdata->id,
						'title' => $pdata->title,
						'url' => $pdata->url,
						'description' => $pdata->desc
					);
					$this->Link_Manager->UpdateLink($mod_link);
					$result = 'SUCC_*';
					break;
				case 'delete':
					$this->Link_Manager->RemoveLink($pdata->id);
					$result = 'SUCC_*';
					break;
				default:
					$result = 'FAIL_*';
					break;
			}
			$this->cache->Remove('blog_link_list_' . $this->_current_blogger_id);
			echo($result);
		} else {
			$this->_check_messages();
			$this->load->view('mgmt/links_view', $this->_view_data);
		}
	}
	
	function links_list($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$links = $this->Blogger_Manager->GetLinks($this->_current_blogger_id);
		$this->_view_data['links_list'] = $links;
		
		$this->load->view('mgmt/links_list_view', $this->_view_data);
	}
	
	function messages($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			// proc posted data
			$oper = $this->input->post('operation');
			$result = '';
			switch($oper) {
				case 'send_pm':
					$pm_data = json_decode($this->input->post('posted_data'));
					$new_pm = array(
						'sender_name' => $this->_blog_info->user_name,
						'to_blogger_id' => $pm_data->to_blogger_id,
						'title' => $pm_data->title,
						'content' => $pm_data->content,
						'sent_time' => $this->common->Now(),
						'sender_email' => '',
						'ip' => $this->input->ip_address(),
						'from_blogger_id' => $this->_current_blogger_id
					);
					$this->Message_Manager->SendPrivateMessage($new_pm);
					$result = 'SUCC_*';
					break;
				case 'delete':
					$pm_id = $this->input->post('pm_id');
					$this->Message_Manager->DeletePM($pm_id);
					$result = 'SUCC_' . $pm_id;
					break;
				default:
					break;
			}
			echo($result);
		} else {
			$this->_check_messages();
			$pms = $this->Message_Manager->GetPMList();
			$this->_view_data['messages_list'] = $pms;
			
			$this->load->view('mgmt/messages_view', $this->_view_data);
		}
	}
	
	function get_message($blogger_uri, $msg_id) {
		$this->_setUp();
		$this->_check_owner();
		
		$pm = $this->Message_Manager->GetPrivateMessage($msg_id);
		$pm->sender_name = $this->common->HTMLSpecChars($pm->sender_name);
		$pm->title = $this->common->HTMLSpecChars($pm->title);
		$pm->content = $this->common->UBBCode($pm->content, FALSE);
//		echo(json_encode($pm));
		
		$this->_check_messages();
		$this->_view_data['message_details'] = $pm;
		$this->load->view('mgmt/messages_details_view', $this->_view_data);
	}
	
	function settings($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$is_post_back = $this->input->post('hidIsPostBack');
		if($is_post_back == 'ja') {
			$pdata = json_decode($this->input->post('posted_data'));
			$result = '';
			if($pdata->title != '' || $pdata->friendPassword != '') {
				$blog_info = array(
					'blogger_id' => $this->_current_blogger_id,
					'title' => $pdata->title,
					'slogan' => $pdata->slogan,
					'friend_password' => $pdata->friendPassword,
					'announcement' => $pdata->announcement,
					'skin_name' => $pdata->theme,
					'allow_public_comment' => $pdata->allowPublicComment
				);
				$this->Blogger_Manager->UpdateBloggerInfo($blog_info);
				$result = 'SUCC_*';
			}
			// clean caches
			$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
			$this->cache->Remove('blogger_list');
			echo($result);
		} else {
			$this->_check_messages();
			
			// check if avatar available
			$user_avatar_filename = 'avt_' . $this->_current_blogger_id . '_48x48.jpg';
			$user_avatar_path = $_SERVER['DOCUMENT_ROOT'] . '/img/avatars/' . $user_avatar_filename;
			if(!file_exists($user_avatar_path)) {
				$user_avatar_filename = 'avt_-1_48x48.jpg';
			}
			$this->_view_data['avatar_filename'] = $user_avatar_filename;
			
			$this->load->view('mgmt/settings_view', $this->_view_data);
		}
	}
	
	function change_password_email($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$is_post_back = $this->input->post('hidIsPostBack');
		$result = '';
		if($is_post_back == 'ja') {
			$oper = $this->input->post('operation');
			switch($oper) {
				case 'ch_password':
					$new_pwd = $this->input->post('new_password');
					if($new_pwd != '') {
						$this->Blogger_Manager->ChangePassword($this->_current_blogger_id, $new_pwd);
						$result = 'SUCC_*';
					}
					break;
				case 'ch_email':
					$new_email = $this->input->post('new_email');
					$this->Blogger_Manager->ChangeEMail($this->_current_blogger_id, $new_email);
					$result = 'SUCC_*';
					break;
				default:
					break;
			}
		}
		$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
		echo($result);
	}
	
	function upload_avatar($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$target_path = $_SERVER['DOCUMENT_ROOT'] . '/img/avatars/' . $this->_current_blogger_id;
		if(!is_dir($target_path)) {
			mkdir($target_path, 0777, TRUE);
		}
		
		$config['upload_path'] = $target_path;
		$config['allowed_types'] = 'jpg';
		$config['max_size'] = '100';
		$config['max_width'] = '512';
		$config['max_height'] = '512';
		
		$this->load->library('upload', $config);
		
		$post_upload_info = array(
			'avatar' => '',
			'error' => ''
		);
		if(!$this->upload->do_upload('filAvtUpload')) {
			$post_upload_info['error'] = $this->upload->display_errors('', '');
		} else { // uploading successful
			$ud = $this->upload->data();
			if($ud['is_image'] == 1) {
				$post_upload_info['avatar'] = $this->_processUploadedAvatar($ud);
				
				// increase Server-side avatar version (so client-side can reload them)
				$avatar_ver_file = $_SERVER['DOCUMENT_ROOT'] . '/data/avatar_ver.txt';
				$old_avatar_version = (int)file_get_contents($avatar_ver_file);
				file_put_contents($avatar_ver_file, (string)($old_avatar_version + 1));
			} else {
				throw new Exception('File is not an image!');
			}
		}
		echo(json_encode($post_upload_info));
	}
	
	function _processUploadedAvatar($avatar_data) {
		$source_path = $avatar_data['full_path'];
		$target_path = $_SERVER['DOCUMENT_ROOT'] . '/img/avatars/avt_' . $this->_current_blogger_id . '_48x48' . strtolower($avatar_data['file_ext']);
		$avatar_filename = basename($target_path);
		
		if($avatar_data['image_width'] == 48 && $avatar_data['image_height'] == 48) {
			copy($source_path, $target_path);
			return $avatar_filename;
		}
		
		// not 48x48? resize!
		$config['image_library'] = 'gd2';
		$config['source_image'] = $source_path;
		$config['new_image'] = $target_path;
		$config['maintain_ratio'] = FALSE;
		$config['width'] = 48;
		$config['height'] = 48;
		
		$this->load->library('image_lib', $config);
		
		if(!$this->image_lib->resize()) {
			throw new Exception('Image processing error!');
		} else {
			return $avatar_filename;
		}
	}
	
	function delete_comment($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$is_post_back = $this->input->post('hidIsPostBack');
		$result = '';
		if($is_post_back == "ja") {
			$entry_id = $this->input->post('entry_id');
			$comment_id = $this->input->post('comment_id');
			
			$this->load->model('Comment_Manager');
			$this->Comment_Manager->SetCurrentBloggerID($this->_current_blogger_id);
			$this->Comment_Manager->SetCurrentEntryID($entry_id);
			
			try {
				$this->Comment_Manager->DeleteComment($comment_id);
				// clean caches!
				$this->cache->Remove('blogger_list');
				$this->cache->Remove('blog_basic_info_' . $this->_current_blogger_id);
				$this->cache->Remove('blog_recent_comment_list_' . $this->_current_blogger_id);
				$this->cache->Remove('blog_recent_entries_' . $this->_current_blogger_id);
				$this->cache->Remove('latest_entries');
				$result = 'SUCC_' . $comment_id;
			} catch(Exception $ex) {
				$result = 'FAIL_No permission!';
			}
		}
		echo($result);
	}
	
	function upload_pix($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$dt = date_parse($this->common->Now());
		$target_path = $_SERVER['DOCUMENT_ROOT'] . '/pix/' . $dt['year'] . '/' . $this->_current_blogger_id;
		if(!is_dir($target_path)) {
			mkdir($target_path, 0777, TRUE);
		}
		
		$config['upload_path'] = $target_path;
		$config['allowed_types'] = 'bmp|gif|jpg|png';
		$config['max_size'] = '1024';
		$config['encrypt_name'] = TRUE;
//		$config['max_width'] = '512';
//		$config['max_height'] = '512';
		
		$this->load->library('upload', $config);
		
		$post_upload_info = array(
			'pix' => '',
			'error' => ''
		);
		if(!$this->upload->do_upload('filPixUpload')) {
			$post_upload_info['error'] = $this->upload->display_errors('', '');
		} else { // uploading successful
			$ud = $this->upload->data();
			if($ud['is_image'] != 1) {
				throw new Exception('File is not an image!');
			}
			$post_upload_info['pix'] = $dt['year'] . '/' . $this->_current_blogger_id . '/' . $ud['file_name'];
		}
		echo(json_encode($post_upload_info));
	}
	
	function upload_pix_dnd($blogger_uri) {
		$this->_setUp();
		$this->_check_owner();
		
		$dt = date_parse($this->common->Now());
		$target_path = $_SERVER['DOCUMENT_ROOT'] . '/pix/' . $dt['year'] . '/' . $this->_current_blogger_id;
		if(!is_dir($target_path)) {
			mkdir($target_path, 0777, TRUE);
		}
		
		$rawdata = file_get_contents('php://input');
		$data = json_decode($rawdata, TRUE);
		$imageBin = $data['filedata'];
		$imageType = $data['filetype'];
		$imageBin = str_replace('data:' . $imageType . ';base64,', '', $imageBin);
		$imageBin = base64_decode($imageBin);
		
		// create a unique filename
		$target_file = $target_path . '/' . $data['filename'];
		$pp = pathinfo($target_file);
		mt_srand();
		$filename_base = md5(uniqid(mt_rand()));
		$filename = $filename_base . '.' . $pp['extension'];
		$target_file = $target_path . '/' . $filename;

		file_put_contents($target_file, $imageBin);
		chmod($target_file, 0777);
		
		$rv = array('pix' => $dt['year'] . '/' . $this->_current_blogger_id . '/' . $filename);
		echo(json_encode($rv));
	}
	
}
?>